package com.google.code.coma.producer.publisher;

import com.google.code.coma.Coma;
import com.google.code.coma.domain.Part;
import com.google.code.coma.space.util.SpaceManager;
import org.mozartspaces.core.*;

import java.net.URI;

/**
 * Part publisher for Mozart spaces
 *
 * @author Bernhard Nickel, bernhard.nickel@gmail.co
 */
public class SpacePartPublisher extends AbstractPartPublisher implements PartPublisher {
    private MzsCore core;

	private Capi capi;

	private ContainerReference containerReference;

    public SpacePartPublisher(String factoryId) {
		super(factoryId);

        core = DefaultMzsCore.newInstance(0);
		capi = new Capi(core);
		try {
			containerReference = SpaceManager.getOrCreateNamedContainer(URI.create("xvsm://localhost:4242"), factoryId + "_" + Coma.PARTS_CONTAINER, capi);
		} catch (MzsCoreException e) {
			core.shutdown(false);
			throw new RuntimeException("Unable to get container", e);
		}
    }

    @Override
    public void publish(Part part)throws Exception {
        capi.write(new Entry(part), containerReference);
    }

    @Override
    public void shutdown() {
        core.shutdown(false);
    }
}
